package com.yiyuplatform.service.wx.impl;

import com.alibaba.fastjson.JSON;
import com.yiyuplatform.config.ResponseMsgConfig;
import com.yiyuplatform.config.WxConfig;
import com.yiyuplatform.form.WxLoginForm;
import com.yiyuplatform.service.wx.WxService;
import com.yiyuplatform.util.DecodeUtil;
import com.yiyuplatform.vo.ErrorVO;
import com.yiyuplatform.vo.WxLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 大龙
 * \* Date: 2021/11/12
 * \* Time: 19:30
 * \* Description:
 * \
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {
    @Autowired
    private WxConfig wxConfig;

    @Override
    public String UserLogin(WxLoginForm wxLoginForm) {
        try {
            Map<String, Object> map = wxConfig.getSessionByCode(wxLoginForm.getCode());
            if (map.isEmpty()) {
                ErrorVO errorVO = new ErrorVO(ResponseMsgConfig.CodeIsEmpty.getCode(), ResponseMsgConfig.CodeIsEmpty.getMsg());
                return JSON.toJSONString(errorVO);
            } else {
                String session_key = map.get("session_key").toString();
                String openId = map.get("openid").toString();
                //Raw Data
                Map<String, Object> rawDataMap = JSON.parseObject(wxLoginForm.getRawData(), HashMap.class);
                String outSignature = DecodeUtil.getSha1(wxLoginForm.getRawData() + session_key);
                if (!wxLoginForm.getSignature().equals(outSignature)) {
                    ErrorVO errorVO = new ErrorVO(ResponseMsgConfig.SignatureError.getCode(), ResponseMsgConfig.SignatureError.getMsg());
                    return JSON.toJSONString(errorVO);
                }
                Map<String, Object> userInfo = wxConfig.getUserInfo(wxLoginForm.getEncrypteData(), session_key, wxLoginForm.getIv());
                // 判断新用户，写入数据库，并写入登录记录表
                /**
                 * code here
                 * */
                // 服务器生成的自定义登录态
                String token = UUID.randomUUID().toString();
                // 写入Redis
                /**
                 * code here
                 * */
                return JSON.toJSONString(new WxLoginVO(token));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorVO errorVO = new ErrorVO(ResponseMsgConfig.RequestError.getCode(), ResponseMsgConfig.RequestError.getMsg());
            return JSON.toJSONString(errorVO);
        }
    }
}
